package io.renren.modules.generator.controller;

import io.renren.common.utils.PageUtils;
import io.renren.common.utils.Query;
import io.renren.common.utils.R;
import io.renren.common.utils.ValidateFileTypeUtil;
import io.renren.common.utils.excel.ExcelUtils;
import io.renren.modules.generator.entity.AddressEntity;
import io.renren.modules.generator.export.AddressExcelDataCreaterImpl;
import io.renren.modules.generator.service.AddressService;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Set;


/**
 * 
 *
 * @author chenshun
 * @email sunlightcs@gmail.com
 * @date 2018-11-27 14:55:22
 */
@RestController
@RequestMapping("generator/address")
public class AddressController {
    @Autowired
    private AddressService addressService;

    @Autowired
    private ExcelUtils excelUtils;
    @Autowired
    private AddressExcelDataCreaterImpl addressExcelDataCreater;

    /**
     * 列表
     */
    @RequestMapping("/list")
    @RequiresPermissions("generator:address:list")
    public R list(@RequestParam Map<String, Object> params){

        Query query = new Query(params);

        List<AddressEntity> list = addressService.queryPage(query);

        int total =addressService.queryPageTotal(params);

        PageUtils pageUtils = new PageUtils(list, total, query.getLimit(), query.getCurrPage());

        return R.ok().put("page", pageUtils);
    }


    /**
     * 信息
     */
    @RequestMapping("/info/{id}")
    public R info(@PathVariable("id") Integer id){
			AddressEntity address = addressService.info(id);

        return R.ok().put("address", address);
    }

    /**
     * 保存
     */
    @CacheEvict(value = {"addressController:queryAllFromAddressAndAllToAddress"},allEntries = true)
    @RequestMapping("/save")
    @RequiresPermissions("generator:address:save")
    public R save(@RequestBody AddressEntity address){
			addressService.save(address);

        return R.ok();
    }

    /**
     * 修改
     */
    @CacheEvict(value = {"addressController:queryAllFromAddressAndAllToAddress"},allEntries = true)
    @RequestMapping("/update")
    @RequiresPermissions("generator:address:update")
    public R update(@RequestBody AddressEntity address){
        addressService.update(address);
        return R.ok();
    }

    /**
     * 删除
     */
    @RequestMapping("/delete")
    @RequiresPermissions("generator:address:delete")
    public R delete(@RequestBody Integer[] ids){
			addressService.deleteBatchIds(Arrays.asList(ids));

        return R.ok();
    }

    /**
     * 更新状态
     * @param ids
     * @return
     */
    @CacheEvict(value = {
            "addressController:queryAllFromAddressAndAllToAddress"},allEntries = true)
    @RequestMapping("/updateStatusByIds")
    @RequiresPermissions("generator:address:status")
    public R updateStatusByIds(@RequestBody Integer[] ids){
        addressService.updateStatusByIds(Arrays.asList(ids));
        return R.ok();
    }

    /**
     * 获取客户的地址关系
     */
    @GetMapping("/queryAddressesByCustomerId/{id}")
    public R queryAddressesByCustomerId(@PathVariable("id") int id){
        List<AddressEntity> addressEntities = addressService.queryAddressesByCustomerId(id);
        return R.ok().put("data",addressEntities);
    }



    /**
     * 获取客户的地址关系
     */
    @GetMapping("/queryFromAddressesAndToAddressesByCustomerId/{id}")
    public R queryFromAddressesAndToAddressesByCustomerId(@PathVariable("id") int id){
        Map<String, List<AddressEntity>> map = addressService.queryAddressByCustomerIdAndByAddressProperty(id);
        return R.ok().put("data",map);
    }


    @GetMapping("/queryEntityByCode")
    public R queryEntityWhereIsEqByCode(@RequestParam String code){
        AddressEntity addressEntity = addressService.queryByCode(code);
        return R.ok().put("data",addressEntity);
    }

    @GetMapping("/queryEntityListByCode")
    public R queryEntityListByCode(@RequestParam String code,@RequestParam String type,@RequestParam Integer customerId){
        List<AddressEntity> addressEntities = addressService.queryEntityListByCode(code,type,customerId);
        return R.ok().put("data",addressEntities);
    }

    /**
     * 查询所有的提货和送货地址
     */
    @Cacheable("addressController:queryAllFromAddressAndAllToAddress")
    @GetMapping("/queryAllFromAddressAndAllToAddress")
    public R queryAllFromAddressAndAllToAddress(){
        Map<String,List<AddressEntity>> map = addressService.queryAllFromAddressAndAllToAddress();
        return R.ok().put("data",map);
    }

    /**
     * 通过到货地id和产品id，查询提货信息
      */

    @GetMapping("queryFromAddressEntityListByToAddressIdAndProductId")
    public R queryFromAddressEntityListByToAddressIdAndProductId(@RequestParam("toAddressId") Integer toAddressId, @RequestParam("productId") Integer productId){
        Set<AddressEntity> addressEntities =addressService.queryFromAddressEntityListByToAddressIdAndProductId(toAddressId,productId);
        return R.ok().put("data",addressEntities);
    }


    @GetMapping("export")
    @RequiresPermissions("generator:address:export")
    public void exportDate(@RequestParam Map<String, Object> params, HttpServletRequest request,
                           HttpServletResponse response) throws Exception {
        String[] lableNames = {"客户代码","中文名称","地址名称","城市代码","省","市","区","详细地址","联系人","联系手机","联系电话","联系邮箱","地址属性","地址类型","备注","预留字段1",
                "预留字段2","预留字段3"};
        String[] columnNames={"customerCode","customerCnName","code","dtAreaOmsMnemonicCode","province","city","area","detailedAddress","linkMan"
                ,"linkManPhone","linkManTelement","linkManEmail","addressProperty","addressType","remark","extendFirst","extendSecond","extendThird"};
        excelUtils.export(response,"数据导出.xlsx",lableNames,columnNames,params,addressExcelDataCreater);

    }


    /**
     * 地址导入
     */
    @PostMapping("/import")
    @RequiresPermissions("generator:address:import")
    public R importFile(@RequestParam("file") MultipartFile file){

        Workbook book = ValidateFileTypeUtil.validate(file);
        if(book == null){
            return R.error();
        }
        try {
            return addressService.importFile(book);
        }catch (DuplicateKeyException d){
            return R.error(d.getMessage());
        }catch (Exception e) {
            e.printStackTrace();
            return R.error();
        }
    }




























}
